//主要上传下载的操作
$(function(){
	// 上传插件的使用
	var name = null;
	var url = 'http://pan.changxiaoyuan.com/index.php';
	//上传的初始化
	var uploader = WebUploader.create({
		 	dnd: "#grad",
			auto:'true',
			swf:'Uploader.swf',
			pick:'#file_upload',
			server: url,
			formData:{'do':'upload'},	
			fileVal:'filename',
			disableGlobalDnd:'true',//文件的拖拽功能
			paste:'document.body',
			fileSizeLimit:'15728640',
			accept:{
				title:'允许上传的文件类型为txt,png,jpe,jpeg,gif,svg,zip,rar'+
				    'exe,mp3,pdf,doc,docx,xls,ppt' ,
				extensions: 'txt,jpg,png,jpeg,gif,svg,zip,rar,exe,mp3,pdf,doc,docx,xls,ppt',
				mimeTypes:'text/plain,image/*,application/zip,application/x-rar-compressed,'
				+'application/octet-stream,application/octet-stream,audio/mpeg,'
				+'application/pdf,application/msword,application/vnd.ms-excel,'
				+'application/vnd.ms-powerpoint'
			},
	    });
	//错误提示信息
	uploader.on('error',function(type){
		if(type === 'Q_EXCEED_SIZE_LIMIT'){
			alert('所传文件超出15M，请重新选择')
		}else if(type === 'Q_TYPE_DENIED'){
			alert('所传文件类型不满足,必须是以下类型txt,png,jpe,jpeg,gif,svg,zip,rar'+
				    'exe,mp3,pdf,doc,docx,xls,ppt');
		}
	});

	uploader.on("dndAccept", function  () {
		var grad = $("#grad");
			

	/**
	 * 检测拖拽物，实现实时显示交互变化
	 * 待拖拽物碰到目标盒子，则目标盒子颜色发生变化
	 */
	 	grad.on('dragenter', function  (e) {
	 		mask.addMask();
	 		

	 		maskEle = grad.find('.mask');	
		 	maskEle.on('dragleave', function  (e) {
	 		    console.log(1);
	 		    mask.removeMask();		
	 	    })

		 	maskEle.on('drop', function  (e) {
	 		    console.log(1);
	 		    mask.removeMask();		
	 	    })
	 	    console.log(maskEle); 	
	 	})	


	 	
		// grad.on('mouseup', function  (e) {
		// 	console.log(1)
		// 	mask.removeMask();
		// })
	 	// maskEle.on('mouseup', function  (e) {
			// mask.removeMask();	 		
	 	// })
	})
	

	uploader.on( 'fileQueued', function( file ) {
	    uploader.md5File( file )
	        .then(function(md5) {
	            $.ajax(url, {
	                type:'POST',
	                dataType: 'json',
	                data: {
	                    do:'FastUpload',
	                    filename:file.name,
	                    md5: md5
	                },
	                success: function( response ) {
	                    // 如果验证已经上传过
	                    if ( response.success ) {
	                        uploader.skipFile( file )
	                        uploadSuccess(response)
	                    }
	                }
	            });
	        });
    });

    // 文件上传过程中创建进度条实时显示。
    uploader.on( 'uploadProgress', function( file, percentage ) {
    	if($('.progress-bar').length){
    		$('.progress-bar').css('width',percentage*100+'%');
    	}else{
    		$('<div class="progress-bar" style="width: 0%;">Uploading...</div>')
    		  .css({marginTop:'10px',background:'#1c98eb',width:percentage*100+'%',letterSpacing:'0',textAlign:'center'})
    		  .appendTo($('#upload li:nth-child(1)'));
    	}	
	});

	// 上传成功后要干的事
    uploader.on('uploadSuccess',function(file,data){
    	uploadSuccess(data)
    });

  
    // 上传成功处理
    function uploadSuccess(data){
        var code = data.code;
    	// 上传成功修改密码
    	if(data.success == true){
	    	var newHtml = "<div class='uploadSucceed'>上传成功</div>"
	                           +"<div><i class='iconfont'>&#xe614;</i></div>"
	                           +"<div class='collect'>"
	                               +"<span >提取密码：</span>"
	                               +"<input  class='password' id='password'>"
	                               +"<button>完成</button>"
	                               +"<div class='fetchCode'>提取码可修改为4-16位数字或字母</div>"
	                               +"<div class='save-date-range'>文件保存期为3天，请尽快下载</div>"
	                               "</div>"
	                     +"</div>";
	                     
	    	$('.upload').html(newHtml);
	    	$(".password").val(code).focus();
	    }else{
	    	console.log(data);
	    	alert(data.msg+'上传失败');
	    }
		// 修改完成发送给后端
	    $('.collect button').bind('click', function(){
	   		 modifyUpload(data);
		});
    }

    //修改密码
    function modifyUpload(data){
		var password = $('.password').val();
    	var code = data.code;
    	//如果两次密码没变就不发送post请求
    	if(code != password){
    		 $.post(url,{'do':'mdcode','code':password,'preCode':code},function(data){
				if(data.success == false){
					alert('请更换验证码');
				}
		    })
    	}
        modifyCode()
    }

    function modifyCode(){
    	var password = $('.password').val();
    	$('.collect button').css('background','#cacaca').html('修改完成');
		$('.fetchCode').html('继续上传').css({
			margin:'8px 107px',width:'75px',height:'25px',
			color:'#fff',paddingTop:'3px',font:'14px Microsoft YaHei',textAlign:'center',
			borderRadius:'5px',background:'#7dc92b',
			cursor:'pointer'
		}).click(function(){
				window.location.reload();
			});
		$('#password').val(password).attr("readOnly",true);
    }

    //查看文件信息
    function showFile(){
    	$.get(url,{'do':'show','code':test},function(data){
			if(data.msg != null){
				alert('验证码输入有误！');
			}else{
				$('.download').html("<div class='describe'>"
									   +"<img src='images/file_icon.png'>"
									   +"<span style='padding-left:8px'></span>"
									+"</div>"
									+"<div class='load' >下载</div>");	
				$('.download span').html(data.name);
				// 确定下载
				download();
			}
		});
    }

	// 下载，要传参数根据后端的接口文档,下载后还能看到验证码定义全局变量test
	var test = '';
	$('.submit').bind('click',  function(event){
		test = $('#code').val();	
		showFile()
	});

    //下载文件, 确定下载
    function download(){
		$('.load').bind('click',function(event){
			$.get(url,{do:'download',code:test},function(data) {
				 if(data.success == false){
				 	$('.download').html('');
			 	    $('<div>下载失败！</div>').css({fontSize:'14px',textAlign:'center',marginTop:'45px'})
			 	                              .append($('<div><i class="iconfont">&#xe614;</i></div>')
			 	                              .css({marginLeft:'-140px'})).appendTo($('.download'));
			 	    $('<div>'+data.msg+'</div>'); 	
				 }else{
				 	downSuccess();
			  	}
			});
		});
    }

    //下载成功显示
    function downSuccess(){
	 	window.location =url+'?do=download&code='+test;
	 	$('.download').html('');
	 	$('<div>下载成功！</div>').css({fontSize:'14px',textAlign:'center',marginTop:'45px'})
	 	                          .append($('<div><i class="iconfont">&#xe614;</i></div>')
	 	                          .css({marginLeft:'-140px'}))
	 	                          .appendTo($('.download'));
	 	$('<div>继续下载</div>').css({
			margin:'8px 107px',width:'75px',height:'25px',
			color:'#fff',margin:'10px 128px',paddingTop:'3px',font:'14px Microsoft YaHei',textAlign:'center',
			borderRadius:'5px',background:'#7dc92b',
			cursor:'pointer'
		}).appendTo($('.download')).click(function(){
			window.location.reload();								
		});
    }
});